﻿// 版权所有 (c) 陆季玼 Leon
global using Acap = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.Windows;
using Demo.View;
using System;
using System.Linq;

namespace LeAcadPlugin.MHEntry.Commands;

internal class RibbonCmd {

    public void Do() {
        Acap.Idle += Acap_Idle;
    }

    private void Acap_Idle(object sender, EventArgs e) {
        //ribbon为空，加载ribbon
        var ribbonControl = Autodesk.Windows.ComponentManager.Ribbon;
        if (ribbonControl != null) {
            Acap.Idle -= Acap_Idle;
            // Load Ribbon/Menu
            RibbonTab ribbonView = new CustomRibbonView();
            ribbonView.Tag = new CustomRibbonViewModel();
            UpdateBinding(ribbonView, ribbonView.Tag);

            RibbonTab? curTab = ribbonControl.Tabs.OfType<RibbonTab>()
                .FirstOrDefault(t => t.Title == ribbonView.Title);
            if (curTab == null) {
                ribbonControl.Tabs.Add(ribbonView);
            } else {
                ribbonView = curTab;
            }

            ribbonView.IsActive = true;
        } else if (Autodesk.Windows.ComponentManager.IsApplicationActive) {
            var ribbonPaletteSet = Autodesk.AutoCAD.Ribbon.RibbonServices.RibbonPaletteSet;
            if (ribbonPaletteSet == null) {
                ribbonPaletteSet = Autodesk.AutoCAD.Ribbon.RibbonServices.CreateRibbonPaletteSet();
                ribbonPaletteSet.Visible = true;
            }
        }
    }

    private static void UpdateBinding(RibbonTab sourceTab, object bindingSource) {
        foreach (var sourcePanel in sourceTab.Panels) {
            foreach (var item in sourcePanel.Source.Items) {
                var properties = item.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                                                 .Where(p => p.PropertyType == typeof(System.Windows.Data.BindingBase))
                                                 .ToArray();
                foreach (var propertyInfo in properties) {
                    if (propertyInfo.GetValue(item) is System.Windows.Data.Binding binding) {
                        if (binding.Source == null) {
                            System.Windows.Data.Binding newBinding = new();
                            newBinding.Source = bindingSource;
                            newBinding.Path = new System.Windows.PropertyPath(binding.Path.Path);
                            propertyInfo.SetValue(item, newBinding);
                        }
                    }
                }
            }
        }
    }
}